package com.hosever.biz.controller;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.hosever.core.AbstractController;
import com.hosever.core.model.Page;
import com.hosever.core.model.PageRequest;
import com.hosever.model.Article;
import com.hosever.model.Tag;
import com.hosever.service.ArticleService;
import com.hosever.service.TagService;

@Controller
@RequestMapping("/biz/article")
public class ArticleControllerBiz extends
	AbstractController<Article, ArticleService> {

	@Autowired
	TagService tagService;
	
	@RequestMapping()
	public String redirect(Model model){
		return "redirect:"+getRelativePath("/list");
	}
	
	/**
	 * 文章管理
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
 	public String articleManager(Model model,PageRequest pageRequest){
		model.addAttribute("nav","articleManager");
		model.addAttribute("tags", tagService.list());
		Page<Article> page = this.service.page(pageRequest);
		model.addAttribute("page", page);
		return getRelativePath("/formList");
	}
	
	@RequestMapping(value="/add" ,method = RequestMethod.POST)
	public String articleAdd(Model model
			,@ModelAttribute("article") Article article
			,@RequestParam(value = "tagIds", required = false)List<String> tagIds){
		List<Tag> tags = new ArrayList<Tag>();
		if(tagIds!=null && !tagIds.isEmpty()){
			for(String id : tagIds){
				tags.add(tagService.findById(id));
			}
		}
		article.setTags(tags);
		this.service.save(article);
		return "redirect:"+getRelativePath("/list");
	}
	@RequestMapping("/del/{id}")
	public String del(@PathVariable("id") String id,Model model) {
		Article a = new Article();
		a.setId(id);
		this.service.del(a);
		return CONTROLLER_REDIRECT+getRelativePath("/list");
	}
}
